<?php

namespace services\buss;

use api\modules\common\services\UploadService;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\buss\Tool;
use common\models\buss\ToolFile;
use common\models\sys\SysFile;
use services\sys\SysFileService;
use Yii;

/**
 * Class ToolFileService
 * @package services\buss
 */
class ToolFileService extends Service
{
    /**
     * 素材库迭代，修复数据【一次性】
     * @return void
     * @throws \yii\db\Exception
     */
    public static function repairData(): void
    {
        /**
         * @var Tool[] $list
         */
        $list = Tool::find()
            ->orderBy(['id' => SORT_ASC])
            ->all();
        $time = time();
        $data = [];
        foreach ($list as $tool) {
            if (empty($tool->preview_image)) {
                continue;
            }

            foreach ($tool->preview_image as $file) {
                $data[] = [
                    $tool->id, ToolFile::TYPE_IMAGE, $file, $time, $time
                ];
            }
            $tool->thumb_image = $tool->preview_image[0];
            $tool->saveAndCheckResult();
        }
        $data && Yii::$app->db->createCommand()->batchInsert(
            ToolFile::tableName(),
            ['tool_id', 'type', 'file', 'created_at', 'updated_at'],
            $data
        )->execute();
    }

    /**
     * 根据工具ID获取工具图片、视频列表
     * @param int $toolId
     * @return ToolFile[]
     */
    public static function getToolFileListByToolId(int $toolId, $type = null): array
    {
        $query = ToolFile::find()
            ->where(['tool_id' => $toolId]);
        if ($type) {
            $query->andWhere(['type' => $type]);
        }
        return $query->orderBy(['id' => SORT_ASC])->all();
    }

    /**
     * 获取工具图片
     * @param int $toolId
     * @return array
     */
    public static function getEditToolImage(int $toolId): array
    {
        $list = self::getToolFileListByToolId($toolId, ToolFile::TYPE_IMAGE);
        $data = [];
        foreach ($list as $toolFile) {
            $data[] = [
                'file' => $toolFile->file,
                'file_url' => UploadService::getFileTrueUrl(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_IMAGE, $toolFile->file),
                'thumb_url' => UploadService::getFileTrueUrl(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_IMAGE, $toolFile->file, SysFile::STATUS_FORMAL, ['min' => 1]),
            ];
        }
        return $data;
    }

    /**
     * 获取工具视频
     * @param int $toolId
     * @return array
     */
    public static function getEditToolVideo(int $toolId): array
    {
        $list = self::getToolFileListByToolId($toolId, ToolFile::TYPE_VIDEO);
        $data = [];
        foreach ($list as $toolFile) {
            $data[] = [
                'file' => $toolFile->file,
                'file_url' => UploadService::getFileTrueUrl(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_VIDEO, $toolFile->file),
                'thumb_url' =>  UploadService::getFileTrueUrl(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_VIDEO, UploadService::getVoiceThumbImageName($toolFile->file)),
            ];
        }
        return $data;
    }

    /**
     * 获取工具视频
     * @param int $toolId
     * @return array
     */
    public static function getToolFileListFormat(int $toolId): array
    {
        $list = self::getToolFileListByToolId($toolId);
        $data = [];
        foreach ($list as $toolFile) {
            $data[] = [
                'id' => $toolFile->id,
                'type' => $toolFile->type,
                'file_url' => UploadService::getFileTrueUrl(SysFile::SITE_TOOL, $toolFile->type == ToolFile::TYPE_IMAGE ? SysFile::MODULE_TOOL_IMAGE : SysFile::MODULE_TOOL_VIDEO, $toolFile->file),
                'thumb_url' =>  $toolFile->type == ToolFile::TYPE_VIDEO
                    ? UploadService::getFileTrueUrl(SysFile::SITE_TOOL,SysFile::MODULE_TOOL_VIDEO, UploadService::getVoiceThumbImageName($toolFile->file))
                    : UploadService::getFileTrueUrl(SysFile::SITE_TOOL,SysFile::MODULE_TOOL_IMAGE, $toolFile->file, SysFile::STATUS_FORMAL, ['min' => 1]),
                'download_num' => $toolFile->download_num,
            ];
        }
        return $data;
    }

    /**
     * 统计工具图片、视频数
     * @param $toolIds
     * @return array
     */
    public static function getStaticsToolNum($toolIds): array
    {
        $toolIds = is_array($toolIds) ? $toolIds : [$toolIds];
        $list = ToolFile::find()
            ->select(['tool_id', 'type', 'count(*) cnt'])
            ->where(['tool_id' => $toolIds])
            ->indexBy(function ($row) {
                return $row['tool_id'].'-'.$row['type'];
            })
            ->groupBy("tool_id,type")
            ->asArray()
            ->all();
        $data = [];
        foreach ($toolIds as $id) {
            $imageIndex = $id.'-'.ToolFile::TYPE_IMAGE;
            $videoIndex = $id.'-'.ToolFile::TYPE_VIDEO;
            $data[$id] = [
                ToolFile::TYPE_IMAGE => $list[$imageIndex]['cnt'] ?? 0,
                ToolFile::TYPE_VIDEO => $list[$videoIndex]['cnt'] ?? 0,
            ];
        }
        return $data;
    }

    /**
     * 获取素材库文件
     * @param int $toolId
     * @param int $type
     * @param string $file
     * @return ToolFile|null
     */
    public static function getToolFile(int $toolId, int $type, string $file): ?ToolFile
    {
        return ToolFile::findOne([
            'tool_id' => $toolId,
            'type' => $type,
            'file' => $file,
        ]);
    }

    /**
     * 更新绑定关系
     * @param int $toolId
     * @param int $type
     * @param array $addFiles 新增文件
     * @param array $delFiles 删除文件
     * @return void
     * @throws \yii\db\Exception
     */
    public static function editModel(int $toolId, int $type, array $addFiles, array $delFiles = []): void
    {
        if ($delFiles) {
            ToolFile::deleteAll([
                'tool_id' => $toolId,
                'type' => $type,
                'file' => $delFiles,
            ]);
        }
        if ($addFiles) {
            $data = [];
            foreach ($addFiles as $file) {
                $data[] = [
                    $toolId, $type, $file,
                    Yii::$app->user->identity->member_id,
                    Yii::$app->user->identity->member->realname,
                    time(),
                    time()
                ];
            }
            Yii::$app->db->createCommand()->batchInsert(
                ToolFile::tableName(),
                ['tool_id', 'type', 'file', 'operation_id', 'operation_name', 'created_at', 'updated_at'],
                $data
            )->execute();
        }
    }
}
